package com.zzb.weikeautosign.socket;

import com.zzb.weikeautosign.console.ConsoleExcutor;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.Socket;

/**
 * socket监听器
 * Created by 瑱彬 on 2016/3/3.
 */
public class ServiceThread extends Thread {
    private static Logger logger = Logger.getLogger(ServiceThread.class);
    private Socket socket;
    private String ipPort;
    public ServiceThread(Socket socket) {
        this.socket = socket;
        this.ipPort = socket.getInetAddress()+":"+socket.getPort();
    }

    BufferedReader is = null;
    BufferedWriter os = null;

    @Override
    public void run() {
        logger.info("新连接连入--"+ipPort);
        try {
            is = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf8"));
            os = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf8"));
            String commend ;
            String ret;
            while ((commend = is.readLine())!= null){
                ret = ConsoleExcutor.execute(commend);
                os.write(ret);
                os.newLine();
                os.flush();
            }
            logger.info("当前连接已关闭--"+ipPort);
        } catch (IOException e) {
            logger.error("当前连接已关闭--"+ipPort);
        } finally {
            close();
        }
    }

    private void close(){
        try {
            if(is != null) is.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        try {
            if(os != null) os.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        try {
            if(socket != null) socket.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

}
